package com.cn.shuangzi.userinfo.common;

import android.os.Handler;
import android.text.TextUtils;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSStsTokenCredentialProvider;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.cn.shuangzi.R;
import com.cn.shuangzi.SZApp;
import com.cn.shuangzi.SZManager;
import com.cn.shuangzi.common.SZConst;
import com.cn.shuangzi.userinfo.bean.UploadInfo;
import com.cn.shuangzi.util.SZToast;
import com.cn.shuangzi.util.SZUtil;
import com.cn.shuangzi.util.SZValidatorUtil;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

public class OSSManager {
    private String endpoint;
    private String bucket;
    private OSSClient oss;
    private String accessKeyId;
    private String secretKeyId;
    private String securityToken;
    private static SimpleDateFormat sfSimpleYearMonth = new SimpleDateFormat("yyyyMMdd");
    private Handler handler;

    public OSSManager(String accessKeyId, String secretKeyId, String securityToken) {
        this(accessKeyId,secretKeyId,securityToken,SZUtil.getAppMetaDataString(SZManager.getInstance().getContext(), SZConst.ENDPOINT),
                SZUtil.getAppMetaDataString(SZManager.getInstance().getContext(), SZConst.BUCKET));
    }

    public OSSManager(String accessKeyId, String secretKeyId, String securityToken,String bucket) {
        this(accessKeyId,secretKeyId,securityToken,SZUtil.getAppMetaDataString(SZManager.getInstance().getContext(), SZConst.ENDPOINT),
                bucket);
    }

    public OSSManager(String accessKeyId, String secretKeyId, String securityToken, String endpoint, String bucket) {
        this.endpoint = endpoint;
        this.bucket = bucket;
        if (TextUtils.isEmpty(endpoint) || TextUtils.isEmpty(bucket)) {
            throw new IllegalArgumentException("endpoint or bucket not init...");
        }
        this.accessKeyId = accessKeyId;
        this.secretKeyId = secretKeyId;
        this.securityToken = securityToken;
        handler = new Handler();
    }

    /**
     * 多文件上传
     *
     * @param uploadInfoList
     * @param listener
     * @return
     */
    public OSSAsyncTask uploadFileList(final List<UploadInfo> uploadInfoList, final OSSMultiUploadProgressListener listener) {
        long totalFileSize = 0;
        long doneFileSize = 0;
        if (SZValidatorUtil.isValidList(uploadInfoList)) {
            UploadInfo uploadInfoCurrent = null;
            for (UploadInfo uploadInfo : uploadInfoList) {
                long fileSize = new File(uploadInfo.getUploadFilePath()).length();
                totalFileSize += fileSize;
                if (uploadInfo.isUploaded()) {
                    doneFileSize += fileSize;
                }
                if (uploadInfoCurrent == null && !uploadInfo.isUploaded()) {
                    uploadInfoCurrent = uploadInfo;
                }
            }
            if (uploadInfoCurrent != null) {
                final long finalDoneSize = doneFileSize;
                final UploadInfo finalUploadInfoCurrent = uploadInfoCurrent;
                final long finalTotalFileSize = totalFileSize;
                return uploadWithObjPath(uploadInfoCurrent.getUploadFilePath(), uploadInfoCurrent.getObjPath(), new OSSUploadProgressListener() {
                    @Override
                    public void onUpload(String uploadFilePath, PutObjectRequest request, final long currentSize, long totalSize) {
                        if (listener != null) {
                            long currentTotal = finalDoneSize + currentSize;
                            listener.onUpload(finalUploadInfoCurrent, currentTotal, finalTotalFileSize);
                        }
                    }

                    @Override
                    public void onSuccess(String uploadFilePath, String objName, PutObjectRequest request, PutObjectResult result) {
                        finalUploadInfoCurrent.setUploaded(true);
                        finalUploadInfoCurrent.setObjName(objName);
                        uploadFileList(uploadInfoList, listener);
                    }

                    @Override
                    public void onFailure(String uploadFilePath) {
                        if (listener != null) {
                            listener.onFailure(finalUploadInfoCurrent);
                        }

                    }
                });
            } else {
                if (listener != null) {
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            listener.onSuccess(uploadInfoList);
                        }
                    });
                }
            }
        }
        return null;
    }

    ;

    /**
     * 用户头像上传用
     *
     * @param uploadFilePath
     * @param listener
     * @return
     */
    @Deprecated
    public OSSAsyncTask uploadWithMD5Verify(final String uploadFilePath, final OSSUploadProgressListener listener) {
        String uid = UUID.randomUUID().toString().replace("-", "");
        String date = sfSimpleYearMonth.format(new Date());
        final String objName = date + "/" + uid + ".jpg";
        return upload(uploadFilePath, objName, listener);
    }

    public OSSAsyncTask uploadWithObjPath(String uploadFilePath, String ojbPath, final OSSUploadProgressListener listener) {
        String name = UUID.randomUUID().toString().replace("-", "");
        String suffix = null;
        try {
            if (uploadFilePath.lastIndexOf(".") > 0) {
                suffix = uploadFilePath.substring(uploadFilePath.lastIndexOf("."));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (TextUtils.isEmpty(suffix)) {
            suffix = ".jpg";
        }
        final String objName = ojbPath + name + suffix;
        return upload(uploadFilePath, objName, listener);
    }

    public OSSAsyncTask upload(final String uploadFilePath, final String objName, final OSSUploadProgressListener listener) {
        if (oss == null) {
            OSSCredentialProvider credentialProvider = new OSSStsTokenCredentialProvider(accessKeyId, secretKeyId, securityToken);
            oss = new OSSClient(SZManager.getInstance().getContext(), endpoint, credentialProvider);
        }
        // 构造上传请求
        PutObjectRequest put = new PutObjectRequest(bucket, objName, uploadFilePath);

        // 异步上传时可以设置进度回调
        put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
            @Override
            public void onProgress(final PutObjectRequest request, final long currentSize, final long totalSize) {
                if (listener != null) {
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            listener.onUpload(uploadFilePath, request, currentSize, totalSize);
                        }
                    });
                }
            }
        });
        OSSAsyncTask ossAsyncTask = oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
            @Override
            public void onSuccess(final PutObjectRequest request, final PutObjectResult result) {
                SZUtil.log("=========================UploadSuccess========================");
                if (listener != null) {
                    if (handler.post(new Runnable() {
                        @Override
                        public void run() {
                            listener.onSuccess(uploadFilePath, objName, request, result);
                        }
                    })) ;
                }
            }

            @Override
            public void onFailure(PutObjectRequest request, ClientException clientException, ServiceException serviceException) {
                SZUtil.log("=========================UploadFailure========================");
                if (listener != null) {
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            SZToast.error(SZApp.getInstance().getString(R.string.error_net_work));
                            listener.onFailure(uploadFilePath);
                        }
                    });
                }
                // 请求异常
                if (clientException != null) {
                    // 本地异常如网络异常等
                    clientException.printStackTrace();
                }
                if (serviceException != null) {
                    serviceException.printStackTrace();
                }
            }
        });
        ossAsyncTask.waitUntilFinished();
        return ossAsyncTask;
    }

    public interface OSSUploadProgressListener {
        void onUpload(String uploadFilePath, PutObjectRequest request, long currentSize, long totalSize);

        void onSuccess(String uploadFilePath, String objName, PutObjectRequest request, PutObjectResult result);

        void onFailure(String uploadFilePath);
    }

    public interface OSSMultiUploadProgressListener {
        void onUpload(UploadInfo uploadInfo, long currentSize, long totalSize);

        void onSuccess(List<UploadInfo> uploadInfoList);

        void onFailure(UploadInfo uploadInfo);
    }
}
